package com.zb.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;

import com.zb.common.po.enums.ResponseCode;
import com.zb.common.po.vo.AjaxResponse;
import com.zb.common.utils.Constants;
import com.zb.common.utils.JacksonMapper;

public class AuthorityFilter implements Filter {
    private final static String[] static_ext = { "js", "css", "jpg", "png",
            "gif", "html", "ico", "vm", "swf" };

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String req_uri = request.getRequestURI();
        HttpSession session = request.getSession();
        String type = req_uri.substring(req_uri.lastIndexOf('.') + 1);
        // 静态资源忽略
        if (ArrayUtils.contains(static_ext, type)) {
            chain.doFilter(req, resp);
            return;
        }
        if (Constants.LOGINURL.equals(req_uri)
                || Constants.VERIFYCODE.equals(req_uri)
                || Constants.AJAXLOGINURL.equals(req_uri)) {
            chain.doFilter(request, resp);
            return;
        }
        Object sessionUserObj = session.getAttribute(Constants.SESSION_KEY);
        if (null == sessionUserObj) {
            if (request.getHeader("x-requested-with") != null
                    && request.getHeader("x-requested-with").equalsIgnoreCase(
                            "XMLHttpRequest")) { // ajax请求
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                AjaxResponse<?> ajaxResponse = new AjaxResponse<Object>();
                ajaxResponse.setResponseCode(ResponseCode.LOGINTIMEOUT);
                ajaxResponse.setErrorMsg("登录超时!");
                writer.print(JacksonMapper.toJson(ajaxResponse));
            } else {
                response.sendRedirect("/login.do");
            }
            return;
        }
        chain.doFilter(request, resp);
        return;
    }

    public void destroy() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }
}
